<!--
 * @Author: 宋绍华
 * @Date: 2024-11-11 17:16:16
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-09 14:12:05
 * @FilePath: \sr_system_manager_ui\src\views\project\mine\edit.vue
 * @Description: 项目详情
-->
<template>
  <div class="publish-notices create-project">
    <div class="create-project-content">
      <div class="title">
        <span>{{ baseInfo?.projectName }}</span>
        <div class="flex items-center mr-10px btns">
          <BtnRender only-show-record :showAudit="!showReviewProcess" :hide-edit="$route.query.mode !== 'view'"
            :role="userStore.currentIdentityCode" :hideView="true"
            :record="{ ...baseInfo, status: baseInfo?.statusTemp }" :projectNature="projectNature"
            :status="baseInfo?.statusTemp" />
          <el-button ml-12px link type='primary' @click="downloadAll">导出</el-button>
        </div>
      </div>
      <div class="flex items-center ml-20px pt-24px">
        <span v-for="item in btnList.filter(i => i.show)" :key="item.id"
          :class="{ 'btn-item-active': btnActive === item.id }" @click="toggleModule(item.id)" class="btn-item">{{
            item.label }}</span>
      </div>
      <div class="publish-notices-content">
        <Edit :isProposal="isProposal" :departmentList="departmentList" :mode="mode" :projectId="projectId"
          :dictList="dictList" :projectNature="projectNature" ref="editRef" v-show="btnActive === 0" />
        <ProjectMember :managerName="baseInfo?.managerName" :mode="mode" :projectId="projectId" :dictList="dictList"
          ref="projectMemberRef" v-if="btnActive === 1" />
        <Cooperative :mode="mode" :projectId="projectId" ref="cooperativeRef" v-if="btnActive === 2" />
        <ProjectBudget :baseInfo="baseInfo" :projectNature="projectNature" :mode="mode" :projectId="projectId" :dictList="dictList"
          ref="projectBudgetRef" v-if="btnActive === 3" />
        <ProjectDoc :mode="$route.query.type === '4' ? 'edit' : mode" :projectId="projectId" :dictList="dictList"
          ref="projectDocRef" v-if="btnActive === 4" />
        <ReviewProcess :show-notices="checkType === 1" :projectId="projectId" :mode="mode" :dictList="dictList"
          ref="reviewProcessRef" v-if="btnActive === 5" />
      </div>
    </div>

    <div class="create-project-btns">
      <div v-if="checkType === 1 && btnActive === 5">
        <el-button type="primary" @click="onEdit">编辑</el-button>
        <el-button @click="onReject">驳回</el-button>
        <el-button @click="onPass" type="primary">通过</el-button>
      </div>
      <div v-else>
        <el-button v-if="mode === 'edit' || $route.query.type === '4' && btnActive === 4" type="primary"
          @click="save">保存</el-button>
        <el-button v-else @click="closePage">关闭</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default defineComponent({
  beforeRouteEnter(to, from, next) {
    to.meta.title = to.query.projectName;
    next()
  }
})
</script>

<script setup lang="ts" name="edit">
import Edit from '../components/MyProject/Edit.vue';
import ProjectMember from '../components/MyProject/ProjectMember.vue';
import Cooperative from '../components/MyProject/Cooperative.vue';
import ProjectBudget from '../components/MyProject/ProjectBudget.vue';
import ProjectDoc from '../components/MyProject/ProjectDoc.vue';
import ReviewProcess from '../components/MyProject/ReviewProcess.vue';

import { exportProjectDetailApi, getDicListApi, projectApproveApproveApi, projectApproveRejectApi } from '@/api/project';
import { BaseSuccessRespDTO, DictionaryListRespVO } from '@/api/project/types';
import { DepartmentPageVO } from '@/api/system/user/type';
import { getDepartmentListReq as getDepartmentListReq } from '@/api/system/user';
import BtnRender from '../components/MyProject/BtnRender.vue'
import { projectNatureEnum, projectStatusEnum } from '@/utils/constEnum';
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()
const showReviewProcess = ref(false)
const userStore = useUserStore()

const btnList = ref([
  {
    label: '基本信息',
    id: 0,
    show: true
  },
  {
    label: '项目成员',
    id: 1,
    show: true
  },
  {
    label: '合作单位',
    id: 2,
    show: true
  },
  {
    label: '项目预算',
    id: 3,
    show: true
  },
  {
    label: '项目文档',
    id: 4,
    show: true
  },
  {
    label: '审核过程',
    id: 5,
    show: computed(() => showReviewProcess.value)
  },
])
const route = useRoute()
const router = useRouter()

const btnActive = ref(0)  // 当前激活的按钮

const editRef = ref()
const projectMemberRef = ref() // 项目成员ref
const cooperativeRef = ref() // 合作单位ref
const projectBudgetRef = ref() // 预算ref
const projectDocRef = ref() // 文档ref
const reviewProcessRef = ref() // 审核ref 


const projectId = computed(() => route.query.projectId as string)
const mode = ref('edit')
const checkType = ref(0)
const departmentList = ref<DepartmentPageVO[]>() // 院/部
const projectStatus = ref(0) // 项目状态

const projectNature = computed(() => {
  return Number(route.query.projectNature || 1)
})

const isProposal = computed(() => { // 是否为立项状态
  return route.query.isProposal
})

const baseInfo = computed(() => editRef.value?.formVal)

// 字典code 1：所属院系（部） 2：统计年度 3：一级学科 4：研究类别 5：项目分类(纵向) 6：项目分类（横向）7：项目类别 8：合作形式 9：国民经济行业 10学科分类11：合同类别（纵向） 12：合同类别（横向）13：职称 14：专业
const dictList = ref<DictionaryListRespVO[]>([])

// 获取相关字典
const { run: getDicList } = useRequest(getDicListApi, {
  manual: true,
  onSuccess: (res: DictionaryListRespVO[]) => {
    dictList.value = res
  }
})

// 获取学院/部列表
const { run: getDepartmentList } = useRequest(getDepartmentListReq, {
  manual: true,
  onSuccess: (res: DepartmentPageVO[]) => {
    res?.forEach((item) => {
      item.title = item.departmentName
      item.value = item.departmentId
    })
    departmentList.value = res
  }
})

// 驳回
const { run: projectApproveReject } = useRequest(projectApproveRejectApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res.isSuccess) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
      proxy.$tab.closePage()
    }
  }
})

// 通过项目
const { run: projectApproveSubmit } = useRequest(projectApproveApproveApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res.isSuccess) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
      proxy.$tab.closePage()
    }
  }
})
// 导出
const { runAsync: exportProjectDetail } = useRequest(exportProjectDetailApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO) => {
    if (res.isSuccess) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
      proxy.$tab.closePage()
    }
  }
})

const downloadAll = async () => {
  const res = await exportProjectDetail({ id: route.query.projectId })
  let blob = new Blob([res.data], { type: 'application/zip' })
  let url = window.URL.createObjectURL(blob)
  const link = document.createElement('a') // 创建a标签
  link.href = url
  link.download = route.query.projectName
  link.click()
  URL.revokeObjectURL(url) // 释放内存
}

const toggleModule = (id) => {
  btnActive.value = id
}

const validateEdit = async () => {
  switch (btnActive.value) {
    case 0:
      return await editRef.value?.createProject(false, true)
    case 1:
      const res = await projectMemberRef.value?.createProjectMember(false, true)
      return res
    case 2: {
      const res = await cooperativeRef.value?.create(false, true)
      return res
    }
    case 3:
      return await projectBudgetRef.value?.create(false, true)
    case 4:
      return ElMessage.success('操作成功！')
    default:
      return true
  }
}

const save = () => {
  // type 纵向传1，横向传2
  validateEdit()
}

const getType = () => {
  let type = projectNature.value === projectNatureEnum.projectNatureHorizontal ? 2 : 5
  const status = Number(route.query.status || 0)
  if (status === projectStatusEnum.submitApproval) {
    type = 1
  }

  return type
}

// 驳回
const onReject = () => {
  console.log('驳回')
  const form = reviewProcessRef.value.checkSheetFormValidate()

  projectApproveReject({
    fileIds: form.fileIds?.map(i => i.id),
    message: form.notices,
    projectId: projectId.value,
    type: getType(),
  })
}

// 通过
const onPass = () => {
  console.log('通过')
  const form = reviewProcessRef.value.checkSheetFormValidate()
  projectApproveSubmit({
    fileIds: form.fileIds?.map(i => i.id),
    message: form.notices,
    projectId: projectId.value,
    type: getType(),
  })
}

// 编辑
const onEdit = () => {
  const { noticeId, projectName, projectNature, id: projectId, status } = baseInfo.value
  let isProposal: any = undefined
  if (noticeId) {
    // 横向
    if (projectNature === projectNatureEnum.projectNatureHorizontal) {
      // 合同待提交、合同审核未通过状态 设置 isProposal 为 true
      isProposal = status === projectStatusEnum.contractWait || status === projectStatusEnum.contractAudit
    } else {
      // 纵向、校级
      // 申报待审核、申报审核未通过状态 设置 isProposal 为 true
      isProposal = status === projectStatusEnum.submitWait || status === projectStatusEnum.submitAudit
    }
  }
  router.push({ path: '/project/mine/edit', query: { isProposal, projectNature, projectId, type: 0, status, mode: 'edit', projectName } }) 
}

const closePage = () => {
  proxy.$tab.closePage()
}

onMounted(() => {
  getDicList({})
  getDepartmentList()
  if (route.query.type) {
    const type = Number(route.query.type)

    btnActive.value = isNaN(type) ? 0 : type
  }
  if (route.query.mode) {
    mode.value = route.query.mode as string
  }

  if (route.query.checkType) {
    checkType.value = Number(route.query.checkType || 1)
  }

  if (route.query.status) {
    projectStatus.value = Number(route.query.status || 0)
  }

  if (route.query.showReviewProcess) {
    showReviewProcess.value = route.query.showReviewProcess
  }
})
</script>

<style lang="scss" scoped>
.publish-notices {
  --at-apply: bg-white h-full;

  .title {
    --at-apply: text-20px font-bold border-b border-#E5E6EB py-16px pl-20px border-b-solid flex justify-between;
  }

  &-content {
    --at-apply: px-20px;
  }
}

.btn-item {
  --at-apply: inline-block text-14px px-16px py-5px rounded-100px bg-#E8F3FF mr-12px cursor-pointer border-#BEDAFF color-#3491FA border;

  &-active {
    --at-apply: text-#fff bg-#57A9FB;
  }
}

.create-project {
  --at-apply: flex flex-col h-full;

  &-btns {
    --at-apply: bg-white flex py-16px items-center justify-center pt-20px pb-20px;
    border-top: 1px solid #E5E6EB;
  }

  &-content {
    --at-apply: flex-1 h-full bg-white overflow-y-auto;
  }
}
</style>